import { ref, watch, onMounted, nextTick } from 'vue'

/**
 * @name: 获取表格body高度
 * @description: 填充和自定义高度不能同时使用
 */

export default function (props, tableRef) {
  const tableHeight = ref('auto') //表格内容高度
  const tableMaxHeight = ref('auto') //表格内容高度
  const tablePlaceholderHeight = ref('auto') //表格内容高度
  const isFill = props.fill || props.maxFill
  //设置填充高度
  const setFillHeight = () => {
    let zoomRatio = 1
    if (window.devicePixelRatio === 1.5) {
      zoomRatio = 0.8
    }
    if (window.devicePixelRatio === 1.25) {
      zoomRatio = 0.9
    }
    const isEmpty = props.dataSource?.length === 0
    const paginationHeight = props.pagination && !isEmpty ? 48 : 0 //分页器高度
    const windowHeight = document.getElementById('app').clientHeight //浏览器高度
    nextTick(() => {
      const paddingHeight = 20 / zoomRatio //底部padding高度
      const tableHeaderHeight = 48 / zoomRatio //表格头部高度
      const toTopHeight = tableRef.value?.$el?.getBoundingClientRect().top + tableHeaderHeight //距离浏览器顶部高度
      const toBottomHeight = paginationHeight + props.extraHeight + paddingHeight //距离浏览器底部高度
      const bodyHeight = windowHeight - toTopHeight - toBottomHeight
      tableHeight.value = props.maxFill ? 'auto' : bodyHeight + 'px'
      tablePlaceholderHeight.value = props.maxFill ? 'auto' : bodyHeight - 18 + 'px'
      tableMaxHeight.value = props.maxFill ? bodyHeight + 'px' : 'auto'
    })
  }

  //设置固定高度
  const setFixedHeight = (val) => {
    tableHeight.value = val + 'px'
  }

  //监听数据变化重设高度
  watch(
    () => props.dataSource?.length,
    () => {
      isFill && setFillHeight()
    }
  )
  watch(
    () => props.height,
    (val) => val && setFixedHeight(val)
  )
  onMounted(() => {
    props.height && setFixedHeight(props.height)
    isFill && setFillHeight()
  })
  return { tableHeight, tableMaxHeight, tablePlaceholderHeight }
}
